package com.guyan.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guyan.entity.Category;
import com.guyan.mapper.CategoryMapper;
import com.guyan.service.CategoryService;
import com.guyan.vo.CategoryTreeVo;
import com.guyan.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ClassName： CategoryServiceImpl
 * Date： 2021/5/31 15:48
 *
 * @author 孤焰
 * @version 1.0
 **/

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> categoryLeafList() {
        return categoryMapper.getLeafList(null);
    }

    @Override
    public PageInfo categoryLeafListPage(Integer page, Integer limit, String search) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(categoryMapper.getLeafList(search));
        return pageInfo;
    }

    @Override
    public ResultVo updateCategoryById(Category category) {
        category.setUpdateTime(new Date());
        int row = categoryMapper.updateCategoryById(category);
        return row > 0 ? ResultVo.success() : ResultVo.error(6000, "类别状态更新失败");
    }

    @Override
    public ResultVo addCategory(Category category) {
        Date date = new Date();
        category.setCreateTime(date);
        category.setUpdateTime(date);

        int row = categoryMapper.addCategory(category);

        return row > 0 ? ResultVo.success(category.getId()) :
                ResultVo.error(6000, category+"，mapper层操作异常，插入类别失败");
    }

    @Override
    public List<CategoryTreeVo> categoryTreeList() {
        List<Category> list = categoryMapper.categoryTreeList();
        List<CategoryTreeVo> categoryTreeList = new ArrayList<>(list.size());
        for (Category category : list) {
            categoryTreeList.add(new CategoryTreeVo(category));
        }
        return categoryTreeList;
    }

    @Override
    public ResultVo delCategory(Integer id) {
        int row = categoryMapper.delCategory(id);
        return row > 0 ? ResultVo.success() : ResultVo.error(6000, "类别删除失败，数据库操作异常");
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryMapper.getCategoryById(id);
    }
}
